package com.study.bigevent.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.study.bigevent.mapper.ArticleMapper;
import com.study.bigevent.pojo.Article;
import com.study.bigevent.pojo.PageBean;
import com.study.bigevent.service.ArticleService;
import com.study.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        // 设置文章的创建时间和更新时间
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        
        // 从ThreadLocal中获取用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = Integer.valueOf(map.get("id").toString()) ;
        
        // 设置文章的创建用户
        article.setCreateUser(userId);
        
        // 调用Mapper层方法，将文章添加到数据库
        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        // 创建分页对象
        PageBean<Article> pb = new PageBean<>();
        
        // 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);
        // 获取当前登录用户ID
        Map<String , Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        // 执行分页查询（PageHelper会自动拦截下一个查询）
        List<Article> as = articleMapper.list(userId,categoryId, state);
        //强制转换为Page对象
        Page<Article> p = (Page<Article>) as;
        // 设置总记录数
        pb.setTotal(p.getTotal());
        // 设置当前页的数据
        pb.setItems(p.getResult());
        // 返回分页结果
        return pb;
    }

    @Override
    public Article findById(Integer id) {
        Article a = articleMapper.findById(id);
        return a;
    }
}